using System;
using System.Linq;
using System.ComponentModel;
using System.Collections.Generic;
using Kingdee.BOS.Util;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;

namespace CZ.PAEZ.SaleManager.FormPlugIns
{
    [Description("工序计划单")]
    [HotUpdate]
    public class OperationPlanning : AbstractBillPlugIn
    {

        public override void BeforeDoOperation(BeforeDoOperationEventArgs e)
        {
            base.BeforeDoOperation(e);
            switch(e.Operation.FormOperation.Operation.ToUpperInvariant())
            {
                case "SUBMIT":
                    Act_BDO_VarifyStoreInPoint(e);
                    break;
            }
        }

        /// <summary>
        /// 提交时验证返工单中是否存在入库点
        /// </summary>
        /// <param name="e"></param>
        private void Act_BDO_VarifyStoreInPoint(BeforeDoOperationEventArgs e)
        {
            string status = this.Model.GetValue("FDocumentStatus").ToString();
            if (status == "Z") return;

            string fid = this.Model.DataObject["Id"].ToString();
            string sql = string.Format(@"
select mo.FID, moe.FEntryId, mo.FIsRework from T_SFC_OPERPLANNING op
inner join T_SFC_OPERPLANNING_LK oplk on oplk.FID = op.FID and FSTableName='T_PRD_MOENTRY'
inner join T_PRD_MOENTRY moe on moe.FENTRYID=oplk.FSId
inner join T_PRD_MO mo on mo.FID=moe.FID
where mo.FIsRework=1 and op.FID={0}", fid);
            var item = DBUtils.ExecuteDynamicObject(Context, sql);
            if (item.Count <= 0) return;
            
            var entry = this.Model.DataObject["Entity"] as DynamicObjectCollection;
            int count = 0;
            foreach(var row in entry)
            {
                var subEntry = row["SubEntity"] as DynamicObjectCollection;
                var results = subEntry
                    .Where(i => i["IsStoreInPoint"].ToString().Equals("True"))
                    .ToArray();
                count += results.Length;
            }

            if (count <= 0)
            {
                e.Cancel = true;
                this.View.ShowErrMessage("返工订单的工序计划至少要包含一个入库点！");
                return;
            }
        }
    }
}
